<?php

namespace App\Console\Commands;

use App\Http\Common\DayTimes;
use App\Http\Common\Globals;
use App\Http\Controllers\Admin\costManagement\InStandardController;
use App\Models\WyBillsTemplateCommand;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class TaskCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'task:send';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '定时生成账单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     * @return mixed
     * @throws Exception
     */
    public function handle()
    {
        // 禁用掉日志
        DB::unsetEventDispatcher();
        Globals::$writeLog = false;
        $time = date("Y-m-d H:i:s");
        // 拿到所有的账单模板里面的需要生成账单的列表 类型为账单，
        $wyBillsTemplateCommand = WyBillsTemplateCommand::whereHas('area.property',function ($query){
            return $query->where('deadline_time','>',DayTimes::getInstance()->now());
        })// 排除掉物业已经过期的，运营商已经被禁用的
            ->WhereHas('area.property.operator',function ($query){
            $query->orWhereNotIn('enable',[2]);
        })
            ->where('style', '周期性')
            ->where("start_time","<",$time)// 时间在两者之间的
            ->where("end_time",">",$time)
            ->get()
            ->all();
        $inStandardController = new InStandardController();
        if ($wyBillsTemplateCommand){
            foreach ($wyBillsTemplateCommand as $k=>$v){
                $this->generateBillByParams($inStandardController,$v);
            }
        }
        // 根据相应的时间来生成 账单 ,生成后就会将当前时间写入 last_generate_time，记录最新生成的时间，
        foreach ($wyBillsTemplateCommand as $k=>$v) {
            $inStandardController->generateBillByTemplate($v);
        }
    }

    /**
     * 通过参数产生账单
     * @param InStandardController $inStandardController
     * @param $wyBillsTemplateCommand
     */
    public function generateBillByParams(InStandardController $inStandardController,$wyBillsTemplateCommand){
        $inStandardController->request = json_decode($wyBillsTemplateCommand->params);
        $inStandardController->templateCommandId = $wyBillsTemplateCommand->id;
        $inStandardController->generateFunction_();
    }
}
